package com.link.base.wechat.wxplatform.service;

import javax.annotation.Resource;

import com.link.base.base.enterprise.model.Enterprise;
import com.link.base.user.model.CoreUser;
import com.link.base.wechat.basic.util.WxCommonUtil;
import com.link.core.basic.service.KeyGenerateService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.RedisUtil;
import com.link.core.util.UserUtil;
import com.link.core.util.redisclient.LinkRedisClient;
import org.springframework.stereotype.Service;
import com.link.base.wechat.wxplatform.dao.mybatis.mapper.WxPlatformMapper;
import com.link.base.wechat.wxplatform.model.WxPlatform;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;


import java.util.List;

/**
 * 微信公众号管理
 *
 * @author 欧阳振强
 * @date 2019/02/27 14:51
 */
@Service
public class WxPlatformServiceImpl extends BasicServiceImpl<WxPlatform> implements WxPlatformService {

    /**
     * 公众号对象存储redisKey前缀
     */
    private static final String AUTHORIZATION_WX_PLATFORM_REDIS_KEY = "authorization_wx_platform_";
    /**
     * 魔法值
     */
    private static final String Y_STR = "Y";

    @Resource
    private WxPlatformMapper wxPlatformMapper;
    @Resource
    private KeyGenerateService keyGenerateService;
    
    @Override
    public BasicMapper<WxPlatform> getBasicMapper() {
        return wxPlatformMapper;
    }

    @Override
    public WxPlatform getWxPlatformByAppId(String wxAppId) throws Exception {
        WxPlatform wxPlatform = new WxPlatform();
        wxPlatform.setWx_app_id(wxAppId);
        WxPlatform record =  wxPlatformMapper.getWxPlatformByAppId(wxPlatform);
        if (record == null) {
            throw new ServiceException("WXPLAT-002", wxAppId);
        }
        return record;
    }

    @Override
    public List<WxPlatform> queryAllNoCorp() throws Exception {
        return wxPlatformMapper.queryAllNoCorp();
    }

    @Override
    public void addWxPlatformFroDevMode(WxPlatform record) throws Exception {
        CoreUser user = UserUtil.getUser();
        record.setPostnId(user.getPostnId());
        record.setOrgId(user.getOrgId());
        record.setValid_flag("Y");
        record.setGrantAuthFlag("Y");
        record.setIs_dev_mode("Y");
        record.setAutoTransConsumer("N");
        record.setId(keyGenerateService.keyGenerate());
        Enterprise enterParam = new Enterprise();
        enterParam.setCode(user.getCorpid());
        Enterprise enterprise = wxPlatformMapper.queryEnterpriseIdByCode(enterParam);
        if (enterprise != null) {
            record.setHead_row_id(enterprise.getId());
        }
        wxPlatformMapper.insert(record);
    }

    @Override
    public void validFlagWxppUpdate(WxPlatform record) throws Exception {
        wxPlatformMapper.validFlagWxppUpdate(record);
    }

    @Override
    public void defaultFlagWxppUpdate(WxPlatform record) throws Exception {
        // 先将默认公众号去除
        wxPlatformMapper.cancelDefaltFlag(record);
        // 设置新的默认公众号
        wxPlatformMapper.defaultFlagWxppUpdate(record);
    }

    @Override
    public void loadAllWxPlatformsToRedis() throws Exception {
        WxPlatform record = new WxPlatform();
        List<WxPlatform> list = wxPlatformMapper.queryAll(record);
        LinkRedisClient j = null;
        try {
            j = RedisUtil.getJedis();
            for (WxPlatform item: list) {
                setWxPlatformToRedis(item, j, AUTHORIZATION_WX_PLATFORM_REDIS_KEY + item.getId());
            }
        } finally {
            RedisUtil.returnResource(j);
        }
    }

    @Override
    public List<WxPlatform> queryAuthPage(WxPlatform record) throws Exception {
        return wxPlatformMapper.queryAuthPage(record);
    }

    @Override
    public WxPlatform countDefaultFlag(WxPlatform record) throws Exception {
        return wxPlatformMapper.countDefaultFlag(record);
    }

    @Override
    public WxPlatform queryDefaultByCorpid(WxPlatform record) throws Exception {
        return wxPlatformMapper.queryDefaultByCorpid(record);
    }

    @Override
    public void grantAuthFlagUpdateCancel(WxPlatform record) throws Exception {
        wxPlatformMapper.grantAuthFlagUpdateCancel(record);
    }

    @Override
    public void upsert(WxPlatform entity) throws Exception {
        WxPlatform num = wxPlatformMapper.countDefaultFlag(entity);
        if (num == null) {
            entity.setPrimary_flag("Y");
            entity.setValid_flag("Y");
        } else if (num != null || !"".equals(num)) {
            if (Y_STR.equals(entity.getPrimary_flag()) && !entity.getId().equals(num.getId())) {
                throw new ServiceException("WXPLAT-003");
            }
        }
        if (isInsertFlag(entity)) {
            entity.setCorpid(entity.getCompany_corp());
            insert(entity);
        } else {
            update(entity);
        }
    }

    /**
     * 将公众号对象写入redis
     *
     * @author ouyangzhenqiang
     * @date 2019/02/28 10:24
     * @param record 公众号对象
     * @param j redis连接对象
     * @param redisKey redisKey
     */
    private void setWxPlatformToRedis(WxPlatform record, LinkRedisClient j, String redisKey) throws Exception {
        j.hset(redisKey, "wx_platform_id", WxCommonUtil.nullToString(record.getId().toString()));
        j.hset(redisKey, "wx_og_id", WxCommonUtil.nullToString(record.getWx_og_id()));
        j.hset(redisKey, "wx_app_id", WxCommonUtil.nullToString(record.getWx_app_id()));
        j.hset(redisKey, "barcode_url", WxCommonUtil.nullToString(record.getBarcode_url()));
        j.hset(redisKey, "wx_pp_accntname", WxCommonUtil.nullToString(record.getWx_pp_accntname()));
        j.hset(redisKey, "wx_pp_type", WxCommonUtil.nullToString(record.getWx_pp_type()));
        j.hset(redisKey, "primary_flag", WxCommonUtil.nullToString(record.getPrimary_flag()));
        j.hset(redisKey, "valid_flag", WxCommonUtil.nullToString(record.getValid_flag()));
        j.hset(redisKey, "comments", WxCommonUtil.nullToString(record.getComments()));
        j.hset(redisKey, "wx_app_redirect_url", WxCommonUtil.nullToString(record.getWx_app_redirect_url()));
        j.hset(redisKey, "wx_app_service_url", WxCommonUtil.nullToString(record.getWx_app_service_url()));
        j.hset(redisKey, "wx_app_secret", WxCommonUtil.nullToString(record.getWx_app_secret()));
        j.hset(redisKey, "wx_app_token", WxCommonUtil.nullToString(record.getWx_app_token()));
        j.hset(redisKey, "wx_encord_aes_key", WxCommonUtil.nullToString(record.getWx_encord_aes_key()));
        j.hset(redisKey, "is_dev_mode", WxCommonUtil.nullToString(record.getIs_dev_mode()));
        j.hset(redisKey, "head_img", WxCommonUtil.nullToString(record.getHeadImg()));
        j.hset(redisKey, "grant_auth_flag", WxCommonUtil.nullToString(record.getGrantAuthFlag()));
        j.hset(redisKey, "auto_trans_consumer", WxCommonUtil.nullToString(record.getAutoTransConsumer()));
    }

    /**
     * 将redis中的公众号数据取出，返回公众号对象信息
     *
     * @author ouyangzhenqiang
     * @date 2019/02/28 10:32
     */
    private WxPlatform getWxPlatformFromRedis(LinkRedisClient j, String redisKey) throws Exception {
        WxPlatform wxPlatform = new WxPlatform();
        wxPlatform.setId(Long.parseLong(j.hget(redisKey, "wx_platform_id")));
        wxPlatform.setWx_og_id(j.hget(redisKey, "wx_og_id"));
        wxPlatform.setWx_app_id(j.hget(redisKey, "wx_app_id"));
        wxPlatform.setBarcode_url(j.hget(redisKey, "barcode_url"));
        wxPlatform.setWx_pp_accntname(j.hget(redisKey, "wx_pp_accntname"));
        wxPlatform.setWx_pp_type(j.hget(redisKey, "wx_pp_type"));
        wxPlatform.setPrimary_flag(j.hget(redisKey, "primary_flag"));
        wxPlatform.setValid_flag(j.hget(redisKey, "valid_flag"));
        wxPlatform.setComments(j.hget(redisKey, "comments"));
        wxPlatform.setWx_app_redirect_url(j.hget(redisKey, "wx_app_redirect_url"));
        wxPlatform.setWx_app_service_url(j.hget(redisKey, "wx_app_service_url"));
        wxPlatform.setWx_app_secret(j.hget(redisKey, "wx_app_secret"));
        wxPlatform.setWx_app_token(j.hget(redisKey, "wx_app_token"));
        wxPlatform.setWx_encord_aes_key(j.hget(redisKey, "wx_encord_aes_key"));
        wxPlatform.setIs_dev_mode(j.hget(redisKey, "is_dev_mode"));
        wxPlatform.setGrantAuthFlag(j.hget(redisKey, "grant_auth_flag"));
        wxPlatform.setAutoTransConsumer(j.hget(redisKey, "auto_trans_consumer"));
        wxPlatform.setHeadImg(j.hget(redisKey, "head_img"));
        return wxPlatform;
    }
}

